import typeToReducer from 'type-to-reducer'
import {
  POST_AUTH_LOGIN,
  POST_AUTH_BIND,
  POST_AUTH_PHONE_LOGIN
} from './../constants/actionTypes'
import {login, logout} from '../services/token'

const initialState = {
  data: null,
  isLoading: false,
  error: false
}


//登录
export const loginReducer = typeToReducer({
  [POST_AUTH_LOGIN]: {
    LOADING: () => ({
      ...initialState,
      isLoading: true,
    }),
    SUCCESS: (state, action) => {
      //store login state
      isLoggedIn = login(action.payload)

      return {
        ...initialState,
        data: action.payload.data,
        isLoggedIn
      }
    },
    ERROR: (state, action) => ({
      ...initialState,
      error: action.payload
    })
  }
}, initialState)


//绑定
export const bindReducer = typeToReducer({
  [POST_AUTH_BIND]: {
    LOADING: () => ({
      ...initialState,
      isLoading: true,
    }),
    SUCCESS: (state, action) => {
      //store login state
      isLoggedIn = login(action.payload)

      return {
        ...initialState,
        data: action.payload.data,
        isLoggedIn
      }
    },
    ERROR: (state, action) => ({
      ...initialState,
      error: action.payload
    })
  }
}, initialState)


//手机验证码登陆
export const phoneLoginReducer = typeToReducer({
  [POST_AUTH_PHONE_LOGIN]: {
    LOADING: () => ({
      ...initialState,
      isLoading: true,
    }),
    SUCCESS: (state, action) => {
      //store login state
      isLoggedIn = login(action.payload)

      return {
        ...initialState,
        data: action.payload.data,
        isLoggedIn
      }
    },
    ERROR: (state, action) => ({
      ...initialState,
      error: action.payload
    })
  }
}, initialState)


